import { h } from './element';
import { cssPrefix } from '../config';
import Button from './button';
import Icon from './icon';
import ColorPick from './colorPick';
import { t } from '../locale/locale';
import {reactive} from './reactive'
import helper from '../core/helper'
//数据处理中心
const $reactive = reactive({list:[],style:{hide:123}});
const btnClick = function (type) {
  if (type !== 'close'){
    let dataCondition = helper.cloneDeep(this.dataCondition)
    this.data.setSelectedCellAttr('dataCondition',dataCondition)
    this.change();
  }
  this.el.hide();
  this.isHide = true;
};
const deleteItem = function(index){
    this.dataCondition.list.splice(index,1);
    render.call(this);
  },
  addItem = function(){
    this.dataCondition.list.push({
      type: 'cell',
      code: '',
      table: '',
      value: '',
      op: '==',
      join: 'and'
    })
    render.call(this);
  },
  addListDom = function(){
    let echo = [],{dataCondition} = this;
    if(dataCondition.list.length == 0)return [''];
    dataCondition.list.forEach((item,index)=>{
      echo.push(h('ul',`${cssPrefix}-dataCondition-item`).children(
        ...addItemDom.call(this,item,index)
      ))
    })
    return echo;
  },
  getCodeOptions = function(item,index){
    let dataDb = this.data.dataDb;
    let codeOptions = []
    dataDb.forEach(db=>{
      if(db.value == item.table){
        db.codes.forEach(code=>{
          codeOptions.push(h('option',`${cssPrefix}-dataCondition-option`).attr({
            label: code.label,
            value: code.value
          }))
        })
      }
    })
    return codeOptions.length == 0?['']:codeOptions;
  },
  addItemDom = function(item,index){
    let echo = [];
    let btnEl = h('li',`${cssPrefix}-dataCondition-delete`).children(
      new Icon('close').on('click', deleteItem.bind(this,index))
    );
    let typeEl = h('li',`${cssPrefix}-dataCondition-li`).children(
      h('label',`${cssPrefix}-dataCondition-label`).html('类型：'),
      h('select',`${cssPrefix}-dataCondition-select`).children(
        h('option',`${cssPrefix}-dataCondition-option`).attr({
          label: '当前值',
          value: 'cell'
        }),
        h('option',`${cssPrefix}-dataCondition-option`).attr({
          label: '数据集',
          value: 'dataDb'
        })
      ).attr({placeholder:'请选择数据集',name:'type'})
      .model($reactive,item,'type')
      .on('change',()=>{
        item.table = '';
        item.code = '';
        if(item.type == 'cell'){
          tableEl.hide();
          codeEl.hide();
        }else{
          tableEl.show();
        }
      })
    );
    let tableEl = h('li',`${cssPrefix}-dataCondition-li`).children(
      h('label',`${cssPrefix}-dataCondition-label`).html('数据集：'),
      h('select',`${cssPrefix}-dataCondition-select`).children(
        ...(()=>{
          let echo = [],dataDb = this.data.dataDb;
          dataDb.forEach(db=>{
            echo.push(h('option',`${cssPrefix}-dataCondition-option`).attr({
              label: db.label,
              value: db.value
            }))
          })
          return echo.length == 0?['']:echo;
        })()
      ).attr({placeholder:'请选择数据集',name:'value'})
        .model($reactive,item,'table')
        .on('change',()=>{
          item.code = '';
          codeSelect.html('').children(
            ...getCodeOptions.call(this,item,index)
          );
          codeEl.show();
        })
    ).hide();
    let codeSelect;
    let codeEl = h('li',`${cssPrefix}-dataCondition-li`).children(
      h('label',`${cssPrefix}-dataCondition-label`).html('字段：'),
      codeSelect = h('select',`${cssPrefix}-dataCondition-select`)
        .attr({placeholder:'请选择字段',name:'code'})
        .model($reactive,item,'code')
    ).hide();
    let opEl = h('li',`${cssPrefix}-dataCondition-li`).children(
      h('label',`${cssPrefix}-dataCondition-label`).html('操作：'),
      h('select',`${cssPrefix}-dataCondition-select`).children(
        h('option',`${cssPrefix}-dataCondition-option`).attr({
          label: '==',
          value: '=='
        }),
        h('option',`${cssPrefix}-dataCondition-option`).attr({
          label: '!=',
          value: '!='
        }),
        h('option',`${cssPrefix}-dataCondition-option`).attr({
          label: '>',
          value: '>'
        }),
        h('option',`${cssPrefix}-dataCondition-option`).attr({
          label: '>=',
          value: '>='
        }),
        h('option',`${cssPrefix}-dataCondition-option`).attr({
          label: '<',
          value: '<'
        }),
        h('option',`${cssPrefix}-dataCondition-option`).attr({
          label: '<=',
          value: '<='
        }),
        h('option',`${cssPrefix}-dataCondition-option`).attr({
          label: 'in',
          value: 'in'
        }),
        h('option',`${cssPrefix}-dataCondition-option`).attr({
          label: 'like',
          value: 'like'
        })
      ).attr({placeholder:'请选择操作',name:'op'})
        .model($reactive,item,'op')
    );
    let valueEl = h('li',`${cssPrefix}-dataCondition-li`).children(
      h('label',`${cssPrefix}-dataCondition-label`).html('比较值：'),
      h('input',`${cssPrefix}-dataCondition-input`)
      .attr({placeholder:'请输入值'})
      .model($reactive,item,'value')
    )
    let connectEl = h('li',`${cssPrefix}-dataCondition-li`).children(
      h('label',`${cssPrefix}-dataCondition-label`).html('条件：'),
      h('select',`${cssPrefix}-dataCondition-select`).children(
        h('option',`${cssPrefix}-dataCondition-option`).attr({
          label: 'and',
          value: 'and'
        }),
        h('option',`${cssPrefix}-dataCondition-option`).attr({
          label: 'or',
          value: 'or'
        })
      ).attr({placeholder:'请选择字段',name:'value'})
        .model($reactive,item,'join')
    );
    if(item.type == 'dataDb'){
      codeSelect.html('').children(
        ...getCodeOptions.call(this,item,index)
      )
      window.codeSelect = codeSelect;
      tableEl.show();
      codeEl.show();
    }
    echo.push(btnEl,typeEl,tableEl,codeEl,opEl,valueEl,connectEl);
    return echo;
  },
  addStyleDom = function(){
    this.styleEl.html('')
    this.styleEl.children(
      h('div',`${cssPrefix}-dataCondition-styleItem`).children(
        h('label',`${cssPrefix}-dataCondition-styleLabel`).html('前景色 ：'),
        new ColorPick(this.dataCondition.style.color)
        .model($reactive,this.dataCondition.style,'color')
      ),
      h('div',`${cssPrefix}-dataCondition-styleItem`).children(
        h('label',`${cssPrefix}-dataCondition-styleLabel`).html('背景色 ：'),
        new ColorPick(this.dataCondition.style.background)
        .model($reactive,this.dataCondition.style,'background')
      ),
      h('div',`${cssPrefix}-dataCondition-styleItem`).children(
        h('label',`${cssPrefix}-dataCondition-styleLabel`).html('状态 ：'),
        h('select',`${cssPrefix}-dataCondition-select`).children(
          h('option',`${cssPrefix}-dataCondition-option`).attr({
            label: '显示',
            value: false
          }),
          h('option',`${cssPrefix}-dataCondition-option`).attr({
            label: '隐藏',
            value: true
          })
        )
        .model($reactive,this.dataCondition.style,'hide')
      )
    )
  },
  render = function(){
    this.listEl.html('');
    this.listEl.children(...addListDom.call(this));
    addStyleDom.call(this);
  };
/**
 * 条件属性数据结构
 * {
 * list : [{
 *    type: cell:当前值 | dataDb：表名.字段名，
 *    table: '',
 *    code: '',表名.字段名
 *    value: ''
 *    op: == != > >= < <= in like
 *    join: and or
 * }],
 * style: {}
 * }
 */
export default class DataCondition{
  constructor(data){
    this.isHide = true;
    this.data = data;
    this.dataCondition = $reactive.proxyData;
    this.el = h('div', `${cssPrefix}-dataCondition`)
      .children(
        h('div',`${cssPrefix}-dataCondition-bar`).children(
          h('div', '-title').child(t('dataCondition.title')),
          h('div', '-right').children(
            h('div', `${cssPrefix}-buttons`).children(
              new Button('close').on('click', btnClick.bind(this, 'close')),
              new Button('ok', 'primary').on('click', btnClick.bind(this, 'ok')),
            ),
          ),
        ),
        h('div',`${cssPrefix}-dataCondition-content`).children(
          h('div',`${cssPrefix}-dataCondition-left`).children(
            h('div',`${cssPrefix}-dataCondition-add`).children(
              new Icon('add').on('click',addItem.bind(this))
            ),
            this.listEl = h('div',`${cssPrefix}-dataCondition-list`)
          ),
          this.styleEl = h('div',`${cssPrefix}-dataCondition-right`),
        )
      ).hide();
  }
  reset(){
    if (this.isHide) return;
    const { data } = this;
    const cellData = data.getSelectedCell() || {};
    let nowCondition = cellData.dataCondition || {};
    this.dataCondition.list = helper.cloneDeep(nowCondition.list||[]);
    this.dataCondition.style = helper.cloneDeep(nowCondition.style || {color:'',hide:false,background:''});
    window.demo123 = this.dataCondition;
    render.call(this);
  }
  resetData(data) {
    this.data = data;
    this.reset();
  }
  open(){
    this.isHide = false;
    this.el.show();
  }
}